<template>
  <div class="tags">
    <el-scrollbar class="scroll-container">
      <el-tag
        size="large"
        v-for="(tag, index) in tagList"
        :key="tag.path"
        class="mx-1"
        :closable="tag.path !== '/home/totalscore'"
        :type="tag.path === defaultUrl ? '' : 'info'"
        @click="handleJump(tag)"
        @close="handleClose(tag, index)"
      >
        {{ tag?.meta?.title }}
      </el-tag>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useTagStore } from '../../../stores/tags.js'

const route = useRoute()
const router = useRouter()
const tagStore = useTagStore()
const { tagList } = storeToRefs(tagStore)

const defaultUrl = ref('/home/totalscore')
watch(route, (newVal) => {
  console.log("newVal",newVal)
  defaultUrl.value = newVal.path === '/home/totalscore' ? '/home/totalscore' : newVal.path

}, { deep: true, immediate: true })

const handleJump = (tag) => {
  if (route.path === tag.path) return
  router.push(tag.path)
}

const handleClose = (tag, index) => {
  console.log("zhixing")
  console.log("tag.path",tag.path)
  console.log("route.path",route.path)
  // 1. 禁止关闭首页标签
  if (tag.path === '/home/totlascore') return

  // 2. 从store中删除标签
  tagStore.delTag(tag)

  // 3. 如果关闭的不是当前激活标签，无需处理路由跳转
  if (route.path !== tag.path) return

  // 4. 获取剩余标签
  const remainingTags = tagList.value
  console.log("remainingTags",remainingTags)

  // 5. 处理不同情况下的跳转逻辑
  if (remainingTags.length === 0) {
    // 情况1：关闭的是最后一个标签，跳转首页
    router.push('/home/totalscore')
  } else if (index >= remainingTags.length) {
    // 情况2：关闭的是最后一个标签（但数组还未更新）
    handleJump(remainingTags[remainingTags.length - 1])
  } else {
    // 情况3：优先跳转同位置标签，其次前一个标签
    const targetTag = remainingTags[index] || remainingTags[index - 1]
    handleJump(targetTag)
  }
}
</script>
<style scoped>


</style>
